package org.oep.widgets;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

public class NumberWidget {
	private Canvas parent;
	
	private int value = 0;
	private int maximum = 0;
	private int minimum = 0;
	private String label;
	private String unit;
	private boolean active = false;
	
	public NumberWidget(Canvas parent, String label, String unit, int maximum, int minimum, int value) {
		this.parent = parent;
		this.maximum = maximum;
		this.minimum = minimum;
		this.value = value;
		this.label = label;
		this.unit = unit;
	}
	
	public void setValue(int value) { 
		this.value = value;
	}
	
	public int getValue() { 
		return value;
	}
	public void setMaximum(int max) { 
		this.maximum = max;
	}
	public void setMinimum(int min) { 
		this.minimum = min;
	}
	public void setLabel(String s) {
		this.label = s;
	}
	
	public void setUnit(String s) {
		this.unit = s;
	}
	
	public void setActive(boolean b) {
		active = b;
	}
	
	public boolean isActive() {
		return active;
	}
	
	public void paint(Graphics g) {
		if(!active) return;
		
		int h = parent.getHeight();
		int w = parent.getWidth();
		
		int boxWidth = w / 2;
		int boxHeight = h / 2;
		int boxTop = h / 4;
		int boxLeft = w / 4;
		
		g.setColor(0xffffff);
		g.fillRect(w / 4, h / 4, w / 2, h / 2);
		g.setColor(0);
		g.drawRect(w / 4, h / 4, w / 2, h / 2);
		
		// Draw the label in the top half.
		String [] tokens = org.oep.widgets.Utils.tokenize(label, ' ');
		String line = new String();
		int currentHeight = g.getFont().getHeight();
		
		for(int i = 0; i < tokens.length /*&& currentHeight <= (boxHeight / 2)*/; i++) {
			char [] chars = (line + tokens[i]).toCharArray();
			int width = g.getFont().charsWidth(chars, 0, chars.length);
			if(width > boxWidth) {
				g.drawString(line, boxLeft + boxWidth / 2, boxTop + currentHeight + 1, Graphics.HCENTER | Graphics.BOTTOM);
				currentHeight += g.getFont().getHeight() + 1;
				line = tokens[i];
			} else {
				line += tokens[i];
			}
			if(i != tokens.length - 1) line += " ";
		}
		if(line.length() > 0)
			g.drawString(line, boxLeft + boxWidth / 2, boxTop + currentHeight + 1, Graphics.HCENTER | Graphics.BOTTOM);
		
		line = "";
		if(this.value > this.minimum) 
			line += "< ";
		line += value;
		if(unit.length() > 0) line += unit;
		if(this.value < this.maximum)
			line += " >";
		
		g.drawString(line, w / 2, boxTop + (3 * boxHeight) / 4, Graphics.HCENTER | Graphics.BOTTOM);
	}
	
	public void increment() {
		if(value < maximum) value++;
	}
	
	public void decrement() {
		if(value > minimum) value--;
	}

}
